package com.sinai.mshab.client.ui.basic;

/**
 * A specification of what characters should be inserted at what positions
 * during data entry to a field.
 * @author serge
 *
 */
public class Mask {
	
	private String mask;
	
	public String getText() {
		return mask;
	}
	
	/**
	 * Creates a new mask.
	 * Create masks like: mmm-mmm/mmm
	 * ignores 'm' and puts - and / at the right indexies.
	 */
	public Mask (String m) {
		mask = m;
	}
	
	/**
	 * Inserts the right character at the right time.
	 * @param s
	 */
	public String applyMask(String s) {
		
		// going through the mask
		for (int i = 0; i < mask.length(); i++) {
			
			// come across an insert char in the mask
			if (mask.charAt(i) != 'm') {
				
				// if it is not already inserted, insert it
				if (s.length() > i && s.charAt(i) != mask.charAt(i)) {
					s = insert(s, mask.charAt(i), i);
				}
			}
		}
		
		
		return s;
	}
	
	public String insert (String s, char c, int index) {
		
		// if its impossible
		if (s.length() < index) {
			return s;
		}
		
		String before = s.substring(0, index);
		String after = s.substring(index);
		return before + c + after;
	}
}
